//
//  PilotTableViewController.m
//  Layout3
//
//  Created by Scott Guyer on 6/22/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//




#import "Character.h"
#import "PilotListViewController.h"
#import "PilotPickerViewController.h"
#import "EVEApi.h"
#import "EditPilotViewController.h"
#import "defs.h"


@implementation PilotListViewController

@synthesize pilotList, editPilotVC, doneBarItem;


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	return [pilotList count];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[self.tableView deselectRowAtIndexPath:indexPath animated:NO];
	[self editPilot:indexPath.row];
}


- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
	[self.tableView deselectRowAtIndexPath:indexPath animated:NO];
	[self editPilot:indexPath.row];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{	
	static NSString *MyIdentifier = @"pilotCells";
	
	CGRect zero = CGRectMake(0,0,0,0);
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:zero reuseIdentifier:MyIdentifier] autorelease];
	}
	
	int row = indexPath.row;
	
	// Configure the cell
	Character* c = [pilotList objectAtIndex:row];
	[cell setText:c.name];
	[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
	[cell setHidesAccessoryWhenEditing:NO];
	
	return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		NSInteger row = indexPath.row;
		[pilotList removeObjectAtIndex:row];
		NSArray* paths = [NSArray arrayWithObject:indexPath];
		[self.tableView deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];

		if ( [pilotList count] > 0 )
			[doneBarItem setEnabled:YES];
		else
			[doneBarItem setEnabled:NO];
	}

}


- (void)setEditing:(BOOL)editing animated:(BOOL)animate
{
	[super setEditing:editing animated:animate];
	[self.tableView reloadData];
}


- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 
{
	NSInteger fromRow = fromIndexPath.row;
	NSInteger toRow = toIndexPath.row;
	
    Character *c = [[pilotList objectAtIndex:fromRow] retain];
    [pilotList removeObjectAtIndex:fromRow];
    [pilotList insertObject:c atIndex:toRow];
	[c release];	
}


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{
	return YES;
}


- (IBAction) addNewPilot:(id)sender
{
	if ( editPilotVC == nil )
	{
		editPilotVC = [[EditPilotViewController alloc] 
					   initWithNibName:@"EditPilotView" bundle:nil];
		if ( editPilotVC == nil )
		{
			// TODO: handle this error
			return;
		}
	}
	
	[editPilotVC.userIDText setText:@""];
	[editPilotVC.apiKeyText setText:@""];
	[editPilotVC.pilotText setText:@""];
	[editPilotVC setDataValid:NO];
	editPilotVC.mode = EditPilotViewModeAdding;
	
	[self.navigationController pushViewController:editPilotVC animated:YES];
	addingPilot = YES;
}


- (void) editPilot:(NSUInteger)idx
{
	Character* c = (Character*)[pilotList objectAtIndex:idx];
	if ( c == nil )
		return;
		
	if ( editPilotVC == nil )
	{
		editPilotVC = [[EditPilotViewController alloc] 
					   initWithNibName:@"EditPilotView" bundle:nil];
		if ( editPilotVC == nil )
		{
			// TODO: handle this error
			return;
		}
	}

	[editPilotVC.userIDText setText:c.userID];
	[editPilotVC.apiKeyText setText:c.apiKey];
	[editPilotVC.pilotText setText:c.name];
	[editPilotVC setDataValid:YES];
	editPilotVC.mode = EditPilotViewModeEditing;
	
	[self.navigationController pushViewController:editPilotVC animated:YES];
	editingPilot = YES;
	editingPilotIndex = idx;
}


- (void) setPilots:(NSMutableArray*)pilots 
{
	pilotList = pilots;
	[pilotList retain];
}


- (void)dealloc 
{
	NSLog(@"%s 0x%x", __FUNCTION__, self);
	
	WIPE( doneBarItem)
	WIPE( editPilotVC)
	WIPE( pilotList)

	[super dealloc];
}


- (void)viewDidLoad {
	[super viewDidLoad];
	[self.tableView setEditing:YES];
	editingPilot = NO;
	addingPilot = NO;
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
}



- (Boolean) isUserUnique:(NSString*)name
{	

	for ( Character* p in pilotList )
	{
		if ( [p.name isEqualToString:name] )
		{
			NSString* msg = [NSString stringWithFormat:@"Pilot '%@' is already in your list.", name];
			
			UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:@"Error" 
															 message:msg
															delegate:self 
												   cancelButtonTitle:@"OK" 
												   otherButtonTitles:nil];
			[alert show];
			[alert release];
		
			return NO;
		}
	}
	
	return YES;
}



- (void)viewWillAppear:(BOOL)animated 
{	
	NSLog(@"%s: viewWillAppear", __FUNCTION__);
	
	[super viewWillAppear:animated];
		
	if ( editingPilot )
	{
		editingPilot = NO;
		
		Character* c = (Character*)[pilotList objectAtIndex:editingPilotIndex];
		if ( c == nil )
			return;  // TODO: This would be a weird error; should log it
		
		if ( editPilotVC == nil )
			return;  // TODO: another weird error
		
		// If the data is the same, do nothing
		if ( [c.userID isEqual:editPilotVC.userIDText.text] &&
			[c.apiKey isEqual:editPilotVC.apiKeyText.text] &&
			[c.name isEqual:editPilotVC.pilotText.text] )
		{
			// A NoOp
			return;
		}
		
		if ( ! editPilotVC.dataIsValid )
		{
//			UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:@"Invalid Data" 
//															 message:@"Unable to update pilot entry.  Please try again."	
//															delegate:self 
//												   cancelButtonTitle:@"OK" 
//												   otherButtonTitles:nil];
//			[alert show];
//			[alert release];			
			return;			
		}
		

		if ( ! [self isUserUnique:editPilotVC.pilotText.text] )
		{
			[editPilotVC.pilotText setText:@""];
			editPilotVC.dataIsValid = NO;
			return;
		}
		
		
		Character* newC = [[Character alloc] init];
		
		newC.userID = [editPilotVC.userIDText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		newC.apiKey = [editPilotVC.apiKeyText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];		
		newC.name = [editPilotVC.pilotText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		newC.charID = [(NSString*)[editPilotVC.charList valueForKey:newC.name] copy];
		
		[pilotList replaceObjectAtIndex:editingPilotIndex withObject:newC];
		[newC release];
	}
	
	
	if ( addingPilot )
	{
		addingPilot = NO;

		if ( ! editPilotVC.dataIsValid )
		{
//			UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:@"Invalid Data" 
//															 message:@"Unable to add pilot(s).  Please try again."	
//															delegate:self 
//												   cancelButtonTitle:@"OK" 
//												   otherButtonTitles:nil];
//			[alert show];
//			[alert release];			
			return;			
		}

		if ( [editPilotVC.addAllSwitch isOn] )
		{
			for ( NSString* charName in [editPilotVC.charList allKeys] )
			{
				if ( ! [self isUserUnique:charName] )
				{
					// TODO: do some messaging to user?
					continue;
				}
				
				Character* newC = [[Character alloc] init];
				
				newC.userID = [editPilotVC.userIDText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
				newC.apiKey = [editPilotVC.apiKeyText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];		
				newC.name = [charName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
				newC.charID = [(NSString*)[editPilotVC.charList valueForKey:newC.name] copy];
				
				[pilotList addObject:newC];		
				[newC release];												
			}
		}
		else
		{
			
			if ( ! [self isUserUnique:editPilotVC.pilotText.text] )
			{
				[editPilotVC.pilotText setText:@""];
				[editPilotVC setDataValid:NO];
				return;
			}
			
			Character* newC = [[Character alloc] init];
			
			newC.userID = [editPilotVC.userIDText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
			newC.apiKey = [editPilotVC.apiKeyText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];		
			newC.name = [editPilotVC.pilotText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
			newC.charID = [(NSString*)[editPilotVC.charList valueForKey:newC.name] copy];
			
			[pilotList addObject:newC];		
			[newC release];	
		}			
		
	}
	
}

- (void)viewDidAppear:(BOOL)animated 
{	
	NSLog(@"%s: viewDidAppear", __FUNCTION__);
	[super viewDidAppear:animated];
	
	if ( [pilotList count] > 0 )
		[doneBarItem setEnabled:YES];
	else
		[doneBarItem setEnabled:NO];
	
	[self.tableView reloadData];	
}

- (void)viewWillDisappear:(BOOL)animated 
{	
	NSLog(@"%s: viewWillDisappear", __FUNCTION__);
}

- (void)viewDidDisappear:(BOOL)animated 
{	
	NSLog(@"%s: viewDidDisappear", __FUNCTION__);
}


@end

